package com.huluobo.day11_im.register.presenter;

import android.text.TextUtils;

import com.huluobo.day11_im.IMApp;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;

public class RegisterPresenter implements RegisterContract.Presenter {
    private RegisterContract.View view;

    public RegisterPresenter(RegisterContract.View view) {
        this.view = view;
    }

    @Override
    public void register(String username, String password, String rePassword) {
        if (username.matches(IMApp.REGEX_USERNAME)) {
            if (password.matches(IMApp.REGEX_PASSWORD)) {
                if (TextUtils.equals(password, rePassword)) {
                    view.onStartRegister();
                    registerEaseMob(username, password);
                } else {
                    view.onRePasswordError();
                }
            } else {
                view.onPasswordError();
            }
        } else {
            view.onUsernameError();
        }
    }

    private void registerEaseMob(String username, String password) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().createAccount(username, password);
                    view.onRegisterSuccess();
                } catch (HyphenateException e) {
                    view.onRegisterFailed(e.getMessage());
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}
